package com.metaaps.eoclipse;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import com.metaaps.eoclipse.api.ILayer;
import com.metaaps.eoclipse.api.ILayerListener;
import com.metaaps.eoclipse.api.ILayerManager;

public class NavigationView extends ViewPart {
	public static final String ID = "EOclipse.navigationView";
	private TreeViewer viewer;
	 

	class ViewContentProvider implements IStructuredContentProvider, 
										   ITreeContentProvider {

        public void inputChanged(Viewer v, Object oldInput, Object newInput) {
		}
        
		public void dispose() {
		}
        
		public Object[] getElements(Object parent) {
			return getChildren(parent);
		}
        
		public Object getParent(Object child) {
			if (child instanceof ILayer) {
				return ((ILayer)child).getParent();
			}
			return null;
		}
        
		public Object[] getChildren(Object parent) {
			if (parent instanceof ILayerManager) {
				return ((ILayerManager)parent).getLayers().toArray();
			}
			return new Object[0];
		}

        public boolean hasChildren(Object parent) {
			return parent instanceof ILayerManager;
		}
	}
	
	class ViewLabelProvider extends LabelProvider {

		public String getText(Object obj) {
			return obj.toString();
		}
		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if (obj instanceof ILayerManager) imageKey = ISharedImages.IMG_OBJ_FOLDER;
			return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
		}
	}

	/**
     * This is a callback that will allow us to create the viewer and initialize
     * it.
     */
	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(((ImageView)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(ImageView.ID)).getRootLayer());
		((ImageView)PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView(ImageView.ID)).addListenner(new ILayerListener() {
			
			@Override
			public void layerRemoved(ILayer l) {
				viewer.refresh();
				
			}
			
			@Override
			public void layerClicked(ILayer l) {
				viewer.refresh();
			}
			
			@Override
			public void layerAdded(ILayer l) {
				viewer.refresh();
				
			}
		});
		
		
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}